<?php
/**
 * Created by PhpStorm.
 * User: ycp
 * Date: 2019/5/23
 * Time: 22:23
 */

namespace app\api\controller;




use app\common\func\Func;
use think\Db;

class Score extends ApiCommon
{
    protected $table = 'store_member';
    protected $levelTable = 'lite_score_level';
    protected $priTable = 'lite_score_privilege';

    public function __construct()
    {
        parent::__construct();
    }

    public function getData()
    {
        $userInfo = db($this->table)->where(['openid' => $this->openid])->find();
        $score = $userInfo['current_score'] = $userInfo['score'] - $userInfo['used_score'];
        $userInfo['level_data'] = Db::table($this->levelTable)->where('start_score', '<=', $score)->where('end_score', '>', $score)->where(['is_deleted' => 0])->field('id,start_score, end_score, show_title')->find();
        //会员等级
        $where = ['level.is_deleted' => 0];
        $array = [];
        $levelData = Db::table($this->levelTable)->where($where)->alias('level')->field('level.*,pri.id as pri_id')
            ->leftJoin('lite_score_level_pri level_pri', 'level.id = level_pri.level_id')
            ->leftJoin('lite_score_privilege pri', 'pri.id = level_pri.pri_id')
            ->select();
        foreach ($levelData as $k => $v){
//            $array[$v['id']]['pri_id'][] = $v['pri_id'];
            $array[$v['id']]['pri_id'][] = $v['pri_id'];
        }
        $priAllData = Db::table($this->priTable)->where(['is_deleted' => 0])
            ->select();

        $levelData = Db::table($this->levelTable)->where($where)->alias('level')
            ->select();

        //变更记录
        $record = Db::table("lite_member_score_record")->where(['open_id' => $this->openid])->select();
        foreach ($record as $k => $value){
            if($value['type'] == 1){
                $record[$k]['type'] = '增加';
            }else{
                $record[$k]['type'] = '减少';
            }
        }


        $res['record'] = $record;
        $res['userInfo'] = $userInfo;
        $res['levelData'] = $levelData;
        $res['priAllData'] = $priAllData;
        $res['array'] = $array;
       $this->success('', $res);
    }

    public function addScore()
    {
        $type = $this->request->param('type');
        if(empty($this->openid)){
            $this->error('请先登录！');
        }
        if($type == 1){
            $dayStart = date("Y-m-d"). " 00:00:00";
            $dayEnd = date("Y-m-d"). " 23:59:59";
            $times = Db::table('lite_member_score_record')->where([
                'open_id' => $this->openid,
            ])->whereBetween("create_time", [$dayStart, $dayEnd])->count();
            if($times < 5){
                Func::addScoreLocal($type, $this->openid);
            }else{
                $this->error('到达增加积分次数！');
            }
        }
        $this->success('');
    }




}